from datetime import datetime
import os
import shutil
import tempfile
from zipfile import ZipFile, ZIP_DEFLATED


def get_timestamp(date=None, with_microseconds=False):
    if not date:
        date = datetime.now()
    stamp = date.strftime("%Y.%d.%m-%H%M%S")
    if with_microseconds:
        # high-resolution formatting options vary from platform to platform, so
        # best to just use the datetime object directory for this
        stamp = "%s.%s" % (stamp, date.microsecond)
    return stamp


def create_zip(zipped_project="", source="", truncate=""):
    """
    Given a path to a .ppf archive to create and the source file or directory
    to create it from, build a zip archive. If truncate has a value and the
    absolute paths to the file/directories under the source start with that
    string, they will be stripped when zipped.

    For instance, if source is "/tmp/stuff/mydir" and truncate is "/tmp/stuff",
    then instead of the contents of the zip being pre-pending with "tmp/stuff",
    they will be prepended with simply "mydir".
    """
    def recursive_zip(zipped_project, directory, folder=""):
        nodes = os.listdir(directory)
        #print "project:", zipped_project
        #print "directory:", directory
        #print "nodes:", nodes
        for item in nodes:
            #print "in for loop..."
            item_path = os.path.join(directory, item)
            archive_item = os.path.join(os.path.basename(source), folder, item)
            #print "item path:", item_path
            #print "exists?", os.path.exists(item_path)
            #print "is dir?", os.path.isdir(item_path)
            #print "archive item:", archive_item
            if os.path.isfile(item_path):
                #print "item:", item
                #print "folder:", folder
                #print "archive item:", archive_item
                zipped_project.write(item_path, archive_item, ZIP_DEFLATED)
                #print zipped_project.namelist()
            elif os.path.isdir(item_path):
                #print "recursing..."
                recursive_zip(
                    zipped_project, os.path.join(directory, item_path), item)

    zipped_project = ZipFile(zipped_project, "w", compression=ZIP_DEFLATED)
    folder = ""
    if truncate:
        folder = source.split(truncate)[1]
    if os.path.isdir(source):
        recursive_zip(zipped_project, source, folder)
    else:
        zipped_project.write(source, folder, ZIP_DEFLATED)
    zipped_project.close()


class TempResources(object):

    def __init__(self):
        self.dirs = []
        self.files = []

    def get_dir(self):
        dir = tempfile.mkdtemp()
        self.dirs.append(dir)
        return dir

    def get_file(self):
        fh, file = tempfile.mkstemp()
        self.files.append(file)
        return file

    def clean_up(self):
        for file in self.files:
            if os.path.exists(file):
                os.unlink(file)
        self.files = []
        for dir in self.dirs:
            if os.path.exists(dir):
                shutil.rmtree(dir)
        self.dirs = []
